package com.excilys.dao;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.excilys.model.Account;

/**
 * 
 * DAO for an account
 * 
 * @author excilys dev : VP, NT
 * 
 */

@Repository
public class AccountDAOHibernateImpl implements IAccountDAO {

	@PersistenceContext
	public EntityManager entityManager;

	/**
	 * {@inheritDoc}
	 */
	public Account getAccountById(long accountId) {
		Query myQuery = entityManager.createQuery("From Account where accountId = :accountId");
		myQuery.setParameter("accountId", accountId);
		Account resultAccount = (Account) myQuery.getSingleResult();
		return resultAccount;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Account getAccountByName(String name) throws NoResultException {
		Query myQuery = entityManager.createQuery("From Account where accountName = :accountName");
		myQuery.setParameter("accountName", name);
		Account resultAccount = (Account) myQuery.getSingleResult();
		return resultAccount;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void updateAccountBalanceByAccountName(String accountName, long accountAmount) {
		Query myQuery = entityManager.createQuery("From Account where accountName = :accountName");
		myQuery.setParameter("accountName", accountName);
		Account resultAccount = (Account) myQuery.getSingleResult();
		resultAccount.setAccountAmount(accountAmount);
		entityManager.flush();
		entityManager.merge(resultAccount);
	}
}
